import hashlib

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render

# Create your views here.
from .models import User


def register(request):
    flag_pass = True
    flag_reged = False
    if request.method == "GET":
        return render(request, 'user/register.html', {'flag_pass': flag_pass, 'flag_reged': flag_reged})
    if request.method == "POST":

        user_name = request.POST.get("user_name")
        user_password = request.POST.get("user_password")
        user_password2 = request.POST.get("user_password2")
        # 查询一下数据库
        old_users = User.objects.filter(username=user_name)
        if user_password != user_password2:
            flag_pass = False
            return render(request, 'user/register.html', {'flag_pass': flag_pass, 'flag_reged': flag_reged})
        elif old_users:
            flag_reged = True
            return render(request, 'user/register.html', {'flag_pass': flag_pass, 'flag_reged': flag_reged})
        else:
            # 注册
            ## 密码加密
            m = hashlib.md5()
            m.update(user_password.encode())
            password_m = m.hexdigest()
            try:
                user = User.objects.create(username=user_name, password=password_m)
            except Exception as e:
                print(f'--create user error as {e}')
                return render(request, 'user/register.html', {'flag_pass': flag_pass, 'flag_reged': flag_reged})

            request.session['username'] = user_name
            request.session['uid'] = user.id
            # TODO 修改session存储时间为1天
            return HttpResponseRedirect('/index')


def login(request):
    # 验证 先验证username是否有
    if request.method == "GET":
        # 检查登陆状态 如果登陆了，显示已经登陆
        if request.session.get('username') and request.session.get('uid'):
            return HttpResponseRedirect('/index')

        # 检查Cookie
        c_username = request.COOKIES.get('username')
        c_uid = request.COOKIES.get('uid')

        if c_username and c_uid:
            # 回写session
            request.session['username'] = c_username
            request.session['uid'] = c_uid
            return HttpResponseRedirect('/index')
        return render(request, 'user/login.html')
    if request.method == "POST":
        username = request.POST.get('user_name')
        password = request.POST.get('user_password')

        try:
            user = User.objects.get(username=username)
        except Exception as e:
            return HttpResponse("用户名或密码错误")

        h = hashlib.md5()
        h.update(password.encode())
        if user.password != h.hexdigest():
            return HttpResponse("用户名或密码错误")

        # 记录会话状态
        request.session['username'] = username
        request.session['uid'] = user.id
        response = HttpResponseRedirect('/index')
        if 'remember' in request.POST:
            response.set_cookie('username', username, 3600 * 24 * 15)
            response.set_cookie('uid', user.id, 3600 * 24 * 15)
        return response


def logout(request):
    if request.session.get('username'):
        del request.session['username']

    if request.session.get('uid'):
        del request.session['uid']

    resp = HttpResponseRedirect('/index')
    if request.COOKIES.get('username'):
        resp.delete_cookie('username')
    if 'uid' in request.COOKIES:
        resp.delete_cookie('uid')

    return resp